//获取应用实例
var common_Js = require("../../../component/common.js")
import Toast from '../../../component/vant/toast/toast';
import Dialog from '../../../component/vant/dialog/dialog';
var app = getApp(), fetchApi = require("../../../utils/httpPost.js");
const format = rate => Math.min(Math.max(rate, 0), 100);
Page({
  data: {
    imgurl:app.getImgUrl(),
    isiphonex: app.globalData.isiphonex,
    isxiaomi: app.globalData.isxiaomi,
    isCollect: false,
    loading: false,
    netWork: false,
    isLoading: true,
    mer:[],
    mer_id:0,
    appraises:[],
    appraiseCount:0,
    pageIndex: 1,
    pageSize: 10,
    carCount:0,
    isShowDialog:false,
    showGetCoupon:false,
    isShowSku:false,
    isShowSkuPop:false,
    products:[],
    product:{},
    chooseSkuTxt:'',
    chooseSkuIndex: 0,
    current:0,
    radioService:'0',
    radioCoupon:'0',
    product_id:0,
    bx_mer_id:0,
    productDetail:[],
    product_count:0,
    totalPrice:0,
    totalOtPrice:0,
    skuStock:0,
    isAllCheck:false,
    chooseSkuId:'',
    chooseSkuImg:'',
    chooseSkuIndex: 0,
    chooseSkuCount: 1,//sku 当前的数量
    chooseSkuTxt:'',
    chooseSku:{},//当前选中的 sku 对象
    chooseSkuAttr:'',
    proprietorSplit:0,
    isLimit:0,
    skuMaxCount:2,
    productInfo:[],//商品基础信息
    productValue:[],//规格列表
    productAttr:[],//规格类型
    categorys:[],
    goBuyType:'buyNow',
    isCollect:false,
    isAppointment:0,
    isVisit:0,
    imgUrls:[],
    orderType:0,
    coupons:[],//商家抵扣券
    gradientColor: {
      '0%': '#ffd01e',
      '100%': '#ee0a24'
    },
    watchAdDetailSecond:15,
    valueCircle:0,
    time: 16 * 1000,
    timeData: {},
    isShowCountDown:true,
    is_add_feed_record:0,
    user_id:0,
    couponDetail:{},
    ag_id:0,
  },
  onLoad: function (options) {
    console.log("options", options)
    var that = this;
    if(options.ag_id){
      this.data.ag_id = parseInt(options.ag_id)
    }
    var mer_id = parseInt(options.id)
    that.data.mer_id = mer_id;
    that.onHttpInit(mer_id)
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpInit: function (mer_id) {
    var that = this
    fetchApi.httpPost('/mer/detail', {
      mer_id: mer_id,
      pageIndex: that.data.pageIndex,
      pageSize: that.data.pageSize,
    }, function (res) {
      if (res.data.code == 0) {
        console.log("商家信息返回数据", res.data.data)
        console.log(' res.data.data.isCollect', res.data.data.isCollect)
        that.data.mer = res.data.data.mer;
        
        // that.data.productAttr = res.data.data.mer.products.productAttr;
        // that.data.product = res.data.data.product;
        // that.data.attrValueCount = res.data.data.product.productAttr.length;

        that.setData({
          mer: res.data.data.mer,
          appraises: res.data.data.appraises,
          appraiseCount: res.data.data.appraiseCount,
          carCount: res.data.data.carCount,
          products: res.data.data.mer.products,
          coupons: res.data.data.mer.coupons,
          is_add_feed_record: res.data.data.is_add_feed_record,
          watchAdDetailSecond: res.data.data.watchAdDetailSecond,
          user_id:res.data.data.user_id,
          time: res.data.data.watchAdDetailSecond!=undefined ? res.data.data.watchAdDetailSecond * 1000: 16* 1000,
          imgUrls: res.data.data.mer.products.length > 0 ? res.data.data.mer.products[0].sliderImageArray : [res.data.data.mer.shopLogo],
          isAppointment: res.data.data.mer.products.length > 0 ? res.data.data.mer.products[0].isAppointment : 0,
          isVisit: res.data.data.mer.products.length > 0 ? res.data.data.mer.products[0].isVisit: 0,
          product_count : res.data.data.mer.productCount,
          isCollect: res.data.data.isCollect > 0 ? true: false,
        });

        that.data.isAppointment = res.data.data.mer.products.length > 0 ? res.data.data.mer.products[0].isAppointment : 0;
        that.data.isVisit = res.data.data.mer.products.length > 0 ? res.data.data.mer.products[0].isVisit: 0;
        
        if(res.data.data.mer.products.length > 0){
          that.data.product_id = res.data.data.mer.products[0].id;
          that.initProductInfo(0)
          that.setData({
            productDetail:res.data.data.mer.products[0]
          });
          console.log('productDetail', that.data.productDetail)
        }else{
          if(res.data.data.mer.coupons.length > 0){
            that.setData({
              current:1
            })
          }
        }
        that.setData({ isLoading: false, loading: true, netWork: true, })
      } else {
        console.log("商家信息返回数据 异常", res.data.msg)
      }
    }, function () {
      that.setData({ isLoading: false, loading: true, netWork: true, })
    })
  },
  goBuy:function(e){
    var that = this
    console.log('chooseSkuId', that.data.chooseSkuId)
    console.log('chooseSkuCount', that.data.chooseSkuCount)

    var that = this;
    var isLogin = app.getStorageSync("isLogin");
    var estate_id = app.getStorageSync("estate_id");
    if (!isLogin) {
      wx.navigateTo({
        url: '/pages/login/index?from_type=product&ag_id' + that.data.ag_id,
      })
    }else {
      if(estate_id == 0){
        this.handleEstate();
      }else{
        if(this.data.chooseSku.id > 0){
          if(this.data.chooseSkuCount <= 0){
            Toast.fail('数量不能为0');
            return;
          }
          that.setData({ visibleModal: false });
          if(that.data.orderType == 0){
            this.onHttpBuy();
          }else{
            this.onHttpBuyCoupon();
          }
        }else{
          Toast.fail('请选择规格');
          return;
        }
      }
    }
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpBuy: function () {
    var that = this
    fetchApi.httpPost('/product/order/addOrderBuyNow', {
      attr_value_id: that.data.chooseSku.id,
      count: that.data.chooseSkuCount,
      order_type: that.data.orderType, //  积分商品订单
    }, function (res) {
      console.log("购买商品 ", res)
      if (res.data.code == 0) {
        var orderId = res.data.data
        wx.redirectTo({
          url: '/pages/pay/paySubmit/index?order_id=' + orderId 
          + "&isAppointment=" + that.data.isAppointment + "&isVisit=" + that.data.isVisit
        })
      } else if(res.data.code == 2){
        that.handleEstate();
      } else {
        console.log("购买商品 异常", res.data.msg)
        Toast.fail(res.data.msg)
      }
    }, function () {
      that.setData({ isLoading: false, loading: true, netWork: true, })
    })
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpBuyCoupon: function () {
    var that = this;
    fetchApi.httpPost('/product/order/addOrderBuyMerCoupon', {
      coupon_id: that.data.coupon_id,
      count: 1,
      order_type: that.data.orderType, //  积分商品订单
    }, function (res) {
      console.log("购买商品 ", res)
      if (res.data.code == 0) {
        var orderId = res.data.data;
        wx.redirectTo({
          url: '/pages/pay/paySubmit/index?order_id=' + orderId 
          + "&isAppointment=" + that.data.isAppointment + "&isVisit=" + that.data.isVisit
        })
      } else if(res.data.code == 2){
        that.handleEstate();
      } else {
        console.log("购买商品 异常", res.data.msg)
        Toast.fail(res.data.msg)
      }
    }, function () {
      that.setData({ isLoading: false, loading: true, netWork: true, })
    })
  },
  // 弹出领取优惠券列表
  getCouponDialog(){
    this.setData({
      showGetCoupon: true
    })
  },
  handleEstate(){
    var that = this;
    var message = "绑定小区后再进行购买"
    Dialog.confirm({
      title: '绑定小区',
      message
    }).then(() => {
      wx.navigateTo({
        url: '/pages/account/index?from_type=product',
      })
    })
    .catch(() => {
      Dialog.close();
    });
  },
  goChooseService:function(){
    var that = this;
    var isLogin = app.getStorageSync("isLogin");
    var estate_id = app.getStorageSync("estate_id");
    if (!isLogin) {
      wx.navigateTo({
        url: '/pages/login/index?from_type=product&ag_id' + that.data.ag_id,
      })
    }else {
      if(estate_id == 0){
        this.handleEstate();
      }else{
        console.log('this.data.product_id',this.data.product_id)
        if(this.data.product_id  > 0){
          this.setData({
            isShowSkuPop: true
          })
        }else{
          Toast.fail('请先选择商家服务')
        }
      }
    }
  },
  goChooseCoupon(){
    var that = this;
    var isLogin = app.getStorageSync("isLogin");
    var estate_id = app.getStorageSync("estate_id");
    if (!isLogin) {
      wx.navigateTo({
        url: '/pages/login/index?from_type=product&ag_id' + that.data.ag_id,
      })
    }else {
      if(estate_id == 0){
        this.handleEstate();
      }else{
        console.log('this.data.coupon_id',this.data.coupon_id)
        if(this.data.coupon_id  > 0){
          this.onHttpBuyCoupon()
        }else{
          Toast.fail('请先选择商家抵扣券')
        }
      }
    }
  },
  closeDialog:function(){
    this.setData({
      showGetCoupon: false
    })
  },
  goUserSaid:function(){
    wx.navigateTo({
      url: '/pages/order/userSaid/index?id=' + this.data.mer_id,
    })
  },
  preImg: function (t) {
    console.log("preSunImg", t)
    var a = t.currentTarget.dataset.imageindex, e = t.currentTarget.dataset.imgdata || [];
    var c = [];
    for (var index in e) {
      c.push(e[index].imgUrl)
    }
    common_Js.preImg(a, c)
  },
  goPhone:function(){
    var that = this
    wx.makePhoneCall({
      phoneNumber: that.data.mer.telphone //仅为示例，并非真实的电话号码
    })
  },
  goLocation:function(){
    var latitude = this.data.mer.latitude
    var longitude = this.data.mer.longitude
    wx.openLocation({
      latitude,
      longitude,
      scale: 17
    })
  },
  /**
   * 显示sku弹框
   */
  showSkuPop:function(e){
    var that = this;
    var isLogin = app.getStorageSync("isLogin");
    var estate_id = app.getStorageSync("estate_id");
    if (!isLogin) {
      wx.navigateTo({
        url: '/pages/login/index?from_type=product&ag_id' + that.data.ag_id,
      })
    } else {
      if(estate_id == 0){
        this.handleEstate();
      }else{
        console.log('showSkuPop e',e)
        var buytype = e.currentTarget.dataset.type;
        this.setData({
          isShowSkuPop:true, 
          goBuyType:buytype
        })
      }
    }
  },
  closeSku: function () {
    this.setData({  isShowSkuPop : false  })
  },
  onClickSku:function(t){
    console.log('onClickSku',t);
    console.log('dataset',t.currentTarget.dataset)
    var dataset = t.currentTarget.dataset;
    var that = this;
    var attrIndex = dataset.attrIndex;
    var valueIndex = dataset.valueIndex;
    that.data.productAttr[attrIndex].chooseValueIndex = valueIndex;
    that.data.productAttr[attrIndex].chooseValue = that.data.productAttr[attrIndex].attrValueArr[valueIndex];

    console.log('that.data.productAttr[attrIndex].chooseValue',that.data.productAttr[attrIndex].chooseValue)
    console.log('that.data.productAttr',that.data.productAttr)
    var sku_txt = that.checkSkuTxt(attrIndex,valueIndex);
    console.log('that.data.product.limitCount',that.data.product.limitCount)
    console.log('that.data.product',that.data.product)
    that.setData({
      productAttr: that.data.productAttr,
      isLimit: that.data.product.isLimit,
      skuMaxCount: that.data.product.limitCount,
      chooseSkuTxt: sku_txt
    })
    that.getChooseSkuAttr()
  },
  checkSkuTxt: function (attrIndex,valueIndex) {
    var that = this;
    var txt = ''
    for (var index in this.data.productAttr) {
      console.log('index',index)
      var attr = this.data.productAttr[index];
      console.log('attr.attrValue[index]',attr.attrValue[index])

      // attr.attrValue[valueIndex].check = false;
      if(attr.chooseValueIndex < 0){
        txt = '';
        break;
      }else{
        txt += attr.chooseValue + ",";
        // attr.attrValue[index].check = true;
      }
      var attrValue = attr.attrValue
      for(var vIndex in attrValue){
        attrValue[vIndex].check = false;
        if(vIndex == valueIndex){
          attr.attrValue[vIndex].check = true;
        }
      }
    }

    console.log('txt',txt)
    console.log('that.data.productValue',that.data.productValue)
    if(txt!=''){
      txt = txt.substring(0,txt.length - 1);
      var sku = that.data.productValue[txt];
      
      var proprietorSplit = sku.proprietorSplit;
      console.log('proprietorSplit',proprietorSplit)

      console.log('sku',sku)
      that.setData({
        // chooseSkuImg: that.data.product.image,
        skuMaxCount: sku.stock,
        chooseSkuTxt: sku.sku,
        totalPrice: Math.round(that.data.chooseSkuCount * sku.price * 100) / 100,  //sku.price ,
        totalOtPrice: Math.round(that.data.chooseSkuCount * sku.otPrice * 100) / 100,//sku.otPrice,
        proprietorSplit:proprietorSplit,
      })
      that.data.chooseSku = sku;
      console.log('sku',sku);
    }
    return txt;
  },
  isAllCheck:function(){
    var isall_check = true
    for (var index in this.data.categorys) {
      if (this.data.categorys[index].check_value_id == '') {
        isall_check = false
      }
    }
    return isall_check;
  },
  getChooseSkuAttr:function(){
    var that = this
    var skuattr = '';
    console.log('that.data.productAttr',that.data.productAttr)
    for (var index in that.data.productAttr){
      skuattr += that.data.productAttr[index].check_value_id + ',';
    }
    if (skuattr != ''){
      skuattr = skuattr.substring(0, skuattr.length - 1)
    }
    that.data.chooseSkuId = skuattr
  },
  //修改购买数量
  skuCountChange({ detail }) {
    var that = this
    console.log('skuCountChange',detail)
    console.log('that.data.chooseSku.price',that.data.chooseSku.price)
    
    if(that.data.chooseSku.price == undefined){
      Toast.fail('请选择规格');
      that.setData({ chooseSkuCount: detail - 1 })
      return;
    }
    var isall_check = that.isAllCheck()
    if (isall_check) {
      that.data.chooseSkuCount = detail;
      that.setData({ chooseSkuCount: detail })
      that.setData({
        totalPrice:  Math.round(detail * that.data.chooseSku.price * 100) / 100,
        totalOtPrice: Math.round(detail * that.data.chooseSku.otPrice * 100) / 100,
      })
    } else {//未选择分类规格， 提示请选择
      Toast.fail('请选择规格');
    }
  },
  handleChange({ detail}) {
    var that = this;
    if(detail.index == 0){
      that.data.orderType = 0;
      that.setData({
        orderType:0,
      })
      this.initProductInfo(0)
    }else{
      var imgs = [];
      that.data.orderType = 3;
      if(this.data.coupons.length > 0){
        this.data.coupon_id = this.data.coupons[0].id;
      }
      that.setData({
        orderType:3,
        imgUrls: [that.data.mer.shopLogo]
      })
      that.goCouponDetail(this.data.coupon_id)
    }
  },
  onChangeRadioService:function(e){
    console.log('onChangeRadioService',e)
    var index = parseInt(e.detail)
    this.initProductInfo(index)
  },
  onChangeRadioCoupon(e){
    console.log('onChangeRadioCoupon',e)
    var index = parseInt(e.detail);
    this.data.coupon_id = this.data.coupons[index].id;
  },
  initProductInfo(index){
    console.log('product',this.data.product);
    this.data.product = this.data.products[index];
    this.data.product_id = this.data.products[index].id

    this.data.productAttr = this.data.product.productAttr;
    this.data.productValue = this.data.product.productValue;
    this.setData({
      product: this.data.product,
      productAttr: this.data.product.productAttr,
      productValue : this.data.product.productValue,
      chooseSkuImg: this.data.product.sliderImageArray[0],
      productInfo:this.data.product,
      imgUrls: this.data.product.sliderImageArray,
      currentState: "1/" + this.data.product.sliderImageArray.length,
      skuStock:this.data.product.totalCount
    });
    this.autoClickSku()
    this.setData({
       radioService: index+'', 
      //  isShowSkuPop:true
    });
    this.goProductDetail(this.data.product_id)
  },
  autoClickSku:function(){
    console.log('autoClickSku');
    var that = this;
    var attrIndex = 0;
    var valueIndex = 0;
    that.data.productAttr[attrIndex].chooseValueIndex = valueIndex;
    that.data.productAttr[attrIndex].chooseValue = that.data.productAttr[attrIndex].attrValueArr[valueIndex];

    // that.data.chooseSkuAttrPrice = that.data.product.attrs[attrIndex].price;
    // that.data.chooseSkuAttrOtPrice = that.data.product.attrs[attrIndex].otPrice;
    
    var sku_txt = that.checkSkuTxt(attrIndex,valueIndex);
    that.setData({
      productAttr: that.data.productAttr,
      skuMaxCount: that.data.product.limitCount,
      chooseSkuTxt: sku_txt,
      // chooseSkuAttrPrice: that.data.chooseSkuAttrPrice,
      // chooseSkuAttrOtPrice: that.data.chooseSkuAttrOtPrice,
    })
    that.getChooseSkuAttr()
  },
  goProductDetail: function(product_id){
    var that = this
    fetchApi.httpPost('/product/detail', {
      product_id: product_id,
    }, function (res) {
      if (res.data.code == 0) {
        console.log("商家服务信息返回数据", res.data.data)
        that.setData({
          productDetail: res.data.data.product,
        });
      } else {
        console.log("商家服务信息返回数据 异常", res.data.msg)
      }
    }, function () {  })
  },
  goCouponDetail: function(coupon_id){
    var that = this
    fetchApi.httpPost('/mer/coupon/detail', {
      coupon_id: coupon_id,
    }, function (res) {
      if (res.data.code == 0) {
        console.log("商家抵扣券信息返回数据", res.data.data);
        var imgs = res.data.data.imgUrl;
        if(imgs!=undefined){
          that.setData({
            imgUrls: [imgs],
          });
        }
        that.setData({
          couponDetail: res.data.data,
        });
      } else {
        console.log("商家抵扣券信息返回数据异常", res.data.msg)
      }
    }, function () {  })
  },
  goPayMoney: function(e){
    console.log('goPayMoney.e',e)
    var that = this
    var isLogin = app.getStorageSync("isLogin");
    if (!isLogin) {
      wx.navigateTo({
        url: '/pages/login/index?from_type=product&ag_id' + that.data.ag_id,
      })
    } else{
      var product_count = that.data.products.length;
      if(product_count > 0){
        wx.navigateTo({
          url: '/pages/pay/paySubmit/index?product_id='+that.data.product_id,
        })
      }else{
        Toast('暂无服务')
      }
    }
  },
  // startTime() {
  //   const countDown = this.selectComponent('.control-count-down');
  //   countDown.start();
  // },
  // finishedTime(){
  //   this.setData({
  //     isShowCountDown: false,
  //   })
  //   this.onHttpAddWatchAd();
  // },
  /**
   * 获取页面数据的 http请求
   */
  // onHttpAddWatchAd: function () {
  //   var that = this
  //   fetchApi.httpPost('/product/watchAd', {
  //     mer_id: that.data.mer_id,
  //     watch_type: 1,
  //   }, function (res) {
  //     console.log("购买商品 ", res)
  //     if (res.data.code == 0) {
  //       Toast.success(res.data.msg);
  //     } else {
  //       // console.log("购买商品 异常", res.data.msg)
  //       // Toast.fail(res.data.msg)
  //     }
  //   }, function () {
  //     that.setData({ isLoading: false, loading: true, netWork: true, })
  //   })
  // },
  // onChange(e) {
  //   console.log('onChange',e);
  //   var seconds = e.detail;
    
  //   const step = 100 / 16;
  //   this.setData({
  //     valueCircle: format((this.data.valueCircle += step))
  //   });

  //   this.setData({
  //     timeData: e.detail
  //   });
  // },
  goHome:function(){
    wx.switchTab({
      url: '../home/home',
    })
  },
  goCollection(res){
    this.onHttpCollection(1)
  },
  goUnCollection(res){
    this.onHttpCollection(0)
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpCollection: function (is_collect) {
    var that = this
    var url = "";
    if(is_collect == 0){//当前为已收藏   执行取消收藏
      url = '/user/collection/delete';
    }else{//当前为未收藏   执行收藏
      url = '/user/collection/add';
    }
    fetchApi.httpPost(url, {
      mer_id: that.data.mer_id,
      collection_type: 1 //  商家收藏
    }, function (res) {
      console.log("收藏商家 ", res)
      if (res.data.code == 0) {
        Toast.success(res.data.msg)
        
        if(is_collect == 0){//当前为已收藏   执行取消收藏
          that.setData({
            isCollect: false
          })
        }else{//当前为未收藏   执行收藏
          that.setData({
            isCollect: true
          })
        }

      } else {
        console.log("收藏商品 异常", res.data.msg)
        Toast.fail(res.data.msg)
      }
    }, function () {
      that.setData({ isLoading: false, loading: true, netWork: true, })
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this;
    var mer_id = this.data.mer_id;
    var user_id = app.getStorageSync("user_id");
    console.log( "转发成功 user_id",user_id)
    return {
      title:that.data.mer.shopName,
      path: '/pages/shop/detail/index?id='+mer_id+'&ag_id='+user_id,
      success: function (res) {
        console.log(res, "转发成功")
      },
      fail: function (res) {
        console.log(res, "转发失败")
      }
    }
  },
})
